﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ThisIsELearning.Model;
using System.Security.Cryptography;

namespace ThisIsELearning.SystemManagement.Controller
{
    /// <summary>
    /// Summary description for UserManagementService
    /// </summary>
    
    [WebService(Namespace = "http://thisiselearning.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class UserManagementService : System.Web.Services.WebService
    {

        [WebMethod]
        public void createParent(string loginId, string password, string fname, string lname, string contactNumber, string email, string address, string gender, string dob, string relationship)
        {
            Parent parent = new Parent();
            parent.loginId = loginId;

            using (MD5 md5Hash = MD5.Create())
            {
                parent.password = SecurityUtils.GetMd5Hash(md5Hash, password);
            }

            parent.firstName = fname;
            parent.lastName = lname;
            parent.contactNumber = contactNumber;
            parent.email = email;
            parent.address = address;
            parent.gender = gender;
            parent.dateRegistered = DateTime.Now;
            parent.dateOfBirth = DateTime.Parse(dob);
            parent.relationship = relationship;

            DataManager manager = new DataManager();
            manager.AddToUsers(parent);
            manager.SaveChanges();
        }

        [WebMethod]
        public bool isUserIdTaken(string loginId)
        {
            DataManager manager = new DataManager();
            var user = from u in manager.Users
                       where u.loginId == loginId
                       select u;

            if (!user.Any())
                return false;

            return true;
        }

        [WebMethod]
        public int createPublishingCompany(string companyName, string address, string phone, string authCode)
        {
            PublishingCompany aCompany = new PublishingCompany();
            aCompany.companyName = companyName;
            aCompany.companyAddress = address;
            aCompany.companyContactNumber = phone;
            aCompany.staffAuthorizationCode = authCode;

            DataManager manager = new DataManager();
            manager.AddToPublishingCompanies(aCompany);
            manager.SaveChanges();

            return aCompany.publishingCompanyId;
        }

        [WebMethod]
        public PublishingCompany[] getPublishingCompanies()
        {
            return DataManagerHelper.getDataManager().PublishingCompanies.ToArray();
        }

        [WebMethod]
        public void deletePublishingCompany(int publishingCompanyId)
        {
            DataManager manager = new DataManager();
            var company = (from c in manager.PublishingCompanies
                           where c.publishingCompanyId == publishingCompanyId
                           select c).First() as PublishingCompany;

            manager.DeleteObject(company);
            manager.SaveChanges();
        }

        [WebMethod]
        public int createPublisher(int publishingCompanyId, string fname, string lname, string gender, string dob, string email, string phone, string username, string password)
        {
            DataManager manager = new DataManager();

            Publisher publisher = new Publisher();
            publisher.firstName = fname;
            publisher.lastName = lname;
            publisher.gender = gender;
            publisher.dateOfBirth = DateTime.Parse(dob);
            publisher.dateRegistered = DateTime.Now;
            publisher.email = email;
            publisher.contactNumber = phone;
            publisher.address = "";
            publisher.loginId = username;

            using (MD5 md5Hash = MD5.Create())
            {
                publisher.password = SecurityUtils.GetMd5Hash(md5Hash, password);
            }

            publisher.publishingCompany = DataManagerHelper.getPublishingCompany(publishingCompanyId);

            manager.AddToUsers(publisher);
            manager.SaveChanges();

            return publisher.userId;
        }

        [WebMethod]
        public int createStudent(int parentId, string fname, string lname, string username, string password, string gender, string dob, string school, int grade, int yearNumber)
        {
            DataManager manager = new DataManager();

            var parent = (from p in manager.Users.OfType<Parent>()
                          where p.userId == parentId
                          select p).First() as Parent;

            Student student = new Student();

            using (MD5 md5Hash = MD5.Create())
            {
                student.password = SecurityUtils.GetMd5Hash(md5Hash, password);
            }

            student.loginId = username;
            student.firstName = fname;
            student.lastName = lname;
            student.contactNumber = parent.contactNumber;
            student.email = parent.email;
            student.address = parent.address;
            student.dateRegistered = DateTime.Now;
            student.parent = parent;
            student.gender = gender;
            student.dateOfBirth = DateTime.Parse(dob);
            student.school = school;
            student.grade = grade;

            LearningProfile emptyLearningProfile = new LearningProfile();
            emptyLearningProfile.creationDate = DateTime.Now;
            student.learningProfile = emptyLearningProfile;

            Subscription defaultSubscription = new Subscription();
            defaultSubscription.subscriptionDate = DateTime.Now;
            defaultSubscription.subscriptionExpiryDate = DateTime.Now.AddYears(yearNumber);
            defaultSubscription.isActivated = false;
            student.subscription = defaultSubscription;

            manager.AddToUsers(student);
            manager.SaveChanges();

            return student.userId;
        }

        [WebMethod]
        public Student[] getStudents(int parentId)
        {
            return DataManagerHelper.listAllStudents().ToArray();
        }

        [WebMethod]
        public Subscription getSubscription(int subscriptionId)
        {
            DataManager manager = new DataManager();

            var subscription = (from s in manager.Subscriptions
                                where s.subscriptionId == subscriptionId
                                select s).First() as Subscription;

            return subscription;
        }

        [WebMethod]
        public void activateSubscription(int subscriptionId)
        {
            DataManager manager = new DataManager();

            Subscription subscription = manager.Subscriptions.Single(s => s.subscriptionId == subscriptionId);
            subscription.isActivated = true;

            //increases expiration date upon activation based on original date assigned.when child created.
            DateTime originalDate = subscription.subscriptionDate;
            DateTime activationDate = DateTime.Now;

            TimeSpan span = activationDate.Subtract(originalDate);

            subscription.subscriptionExpiryDate = subscription.subscriptionExpiryDate.Add(span);
            manager.SaveChanges();
        }

        [WebMethod]
        public void deleteStudent(int studentUserId)
        {
            DataManager manager = new DataManager();

            var student = manager.Users.OfType<Student>().Single(c => c.userId == studentUserId);
            manager.DeleteObject(student.subscription);
            manager.DeleteObject(student.learningProfile);
            manager.DeleteObject(student);

            manager.SaveChanges();
        }

        [WebMethod]
        public void updateStudent(int studentUserId, string fname, string lname, string password, string gender, string dob, string school, int grade, int yearNumber)
        {
            DataManager manager = new DataManager();

            var student = manager.Users.OfType<Student>().Single(c => c.userId == studentUserId);

            student.firstName = fname;
            student.lastName = lname;

            using (MD5 md5Hash = MD5.Create())
            {
                student.password = SecurityUtils.GetMd5Hash(md5Hash, password);
            }

            student.gender = gender;
            student.dateOfBirth = DateTime.Parse(dob);
            student.school = school;
            student.grade = grade;

            if (yearNumber != 0)
            {
                student.subscription.subscriptionDate = DateTime.Now;
                student.subscription.subscriptionExpiryDate = DateTime.Now.AddYears(yearNumber);
            }

            manager.SaveChanges();
        }


    }
}
